﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using System.Collections;

using Future.Enums;
using System.Reflection;
using Future.Common;

namespace Future.FormBase
{
    /// <summary>
    /// 数据操作窗体.
    /// </summary>
    public partial class frmBaseDataForm : frmBaseChild, IDataOperatable, IPrintableForm
    {
        /// <summary>
        /// 当显示明细页面时,首先获取焦点的编辑框.
        /// </summary>
        protected Control _ActiveEditor;

        /// <summary>
        /// 主表的数据表格,由派生类赋值。
        /// 因DevGrid不可继承所以子类窗体Load的时候需要赋值.
        /// </summary>
        protected GridView _SummaryView;

        /// <summary>
        /// 数据编辑页面的控件容器
        /// 因继承,需要在子类窗体Load的时候需要赋值
        /// </summary>
        protected GroupControl _DetailGroupControl;

        /// <summary>
        /// 数据操作状态
        /// </summary>
        protected Enums.UpdateType _UpdateType = Enums.UpdateType.None;

        public frmBaseDataForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 表格是否有数据
        /// </summary>
        /// <returns></returns>
        public virtual bool HasData() { return false; }


        /// <summary>
        /// 初始化数据窗体的常用按钮
        /// </summary>
        public override void InitButtons()
        {
            base.InitButtons();

            IButtonInfo[] dataButton = this.GetDataOperatableButtons();
            IButtonInfo[] printButton = this.GetPrintableButtons();

            this.Buttons.AddRange(dataButton);
            this.Buttons.AddRange(printButton);
        }

        #region IDataOperatable 成员

        public IButtonInfo[] GetDataOperatableButtons()
        {
            ArrayList list = new ArrayList();
            list.Add(this.ToolbarRegister.CreateButton("btnView", "查看", Resource._24_ViewContent.ToBitmap(), new Size(57, 28), this.DoViewContent, true));
            list.Add(this.ToolbarRegister.CreateButton("btnAdd", "新增", Resource._24_Add.ToBitmap(), new Size(57, 28), this.DoAdd));
            list.Add(this.ToolbarRegister.CreateButton("btnDelete", "禁用", Resource._24_Delete.ToBitmap(), new Size(57, 28), this.DoDelete));
            list.Add(this.ToolbarRegister.CreateButton("btnEdit", "修改", Resource._24_Edit.ToBitmap(), new Size(57, 28), this.DoEdit));
            list.Add(this.ToolbarRegister.CreateButton("btnSave", "保存", Resource._24_Save.ToBitmap(), new Size(57, 28), this.DoSave, true));
            list.Add(this.ToolbarRegister.CreateButton("btnCancel", "取消", Resource._24_Cancel.ToBitmap(), new Size(57, 28), this.DoCancel));
            IButtonInfo[] ii = (IButtonInfo[])list.ToArray(typeof(IButtonInfo));
            return ii;
        }
        /// <summary>
        /// 查看选中记录的数据
        /// </summary>
        /// <param name="sender"></param>
        public virtual void DoViewContent(IButtonInfo button)
        {
            this.ButtonStateChanged(_UpdateType);

        }
        /// <summary>
        /// 新增记录
        /// </summary>
        /// <param name="sender"></param>
        public virtual void DoAdd(IButtonInfo button)
        {
            this._UpdateType = UpdateType.Add;
            this.SetEditMode();
            this.ButtonStateChanged(_UpdateType);

        }
        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="sender"></param>
        public virtual void DoEdit(IButtonInfo button)
        {
            this._UpdateType = UpdateType.Update;
            this.SetEditMode();
            this.ButtonStateChanged(_UpdateType);
        }
        /// <summary>
        /// 取消新增或修改
        /// </summary>
        /// <param name="sender"></param>
        public virtual void DoCancel(IButtonInfo button)
        {
            try
            {
                _UpdateType = UpdateType.None;
                this.SetViewMode();
                this.ButtonStateChanged(_UpdateType);
                if (_UpdateType == UpdateType.Add)
                    this.ShowSummaryPage(true);
                else if (_SummaryView.RowCount > 0)
                    this.DoViewContent(button);
            }
            catch (Exception ex) { Common.Msg.ShowException(ex); }
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="sender"></param>
        public virtual void DoSave(IButtonInfo button)
        {
            this._UpdateType = Enums.UpdateType.None;
            this.SetViewMode();
            this.ShowDetailPage(false);
            this.ButtonStateChanged(_UpdateType);
        }
        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="sender"></param>
        public virtual void DoDelete(IButtonInfo button)
        {
        }
        /// <summary>
        /// 数据操作状态
        /// </summary>
        public Enums.UpdateType UpdateType
        {
            get { return _UpdateType; }
        }
        /// <summary>
        /// 是否数据发生改变
        /// </summary>
        public bool DataChanged
        {
            get { return (_UpdateType == Enums.UpdateType.Add) || (_UpdateType == Enums.UpdateType.Update); }
        }

        #endregion

        #region IPrintableForm 成员

        public IButtonInfo[] GetPrintableButtons()
        {
            IButtonInfo[] b = new IButtonInfo[2];
            b[0] = this.ToolbarRegister.CreateButton("btnPrint", "打印", Resource._24_Print.ToBitmap(), new Size(57, 28), this.DoPrint, true);
            b[1] = this.ToolbarRegister.CreateButton("btnPreview", "预览", Resource._24_PrintPreview.ToBitmap(), new Size(57, 28), this.DoPreview);
            return b;
        }
        /// <summary>
        /// 打印预览
        /// </summary>
        /// <param name="button"></param>
        public virtual void DoPreview(IButtonInfo button)
        {
        }
        /// <summary>
        /// 打印报表
        /// </summary>
        /// <param name="button"></param>
        public virtual void DoPrint(IButtonInfo button)
        {
        }

        #endregion

        /// <summary>
        /// 按钮状态发生变化
        /// </summary>        
        protected virtual void ButtonStateChanged(Enums.UpdateType currentState) { }

        /// <summary>
        ///数据操作两种状态.1：数据修改状态 2：查看数据状态 
        ///->设置为编辑模式
        /// </summary>
        protected virtual void SetEditMode()
        {
            Buttons.GetButtonByName("btnView").Enable = false;
            Buttons.GetButtonByName("btnAdd").Enable = false;
            Buttons.GetButtonByName("btnDelete").Enable = false;
            Buttons.GetButtonByName("btnEdit").Enable = false;
            Buttons.GetButtonByName("btnPrint").Enable = false;
            Buttons.GetButtonByName("btnPreview").Enable = false;
            Buttons.GetButtonByName("btnSave").Enable = true;
            Buttons.GetButtonByName("btnCancel").Enable = true;
        }

        /// <summary>
        ///数据操作两种状态.1：数据修改状态 2：查看数据状态 
        ///->设置为查看模式
        /// </summary>
        protected virtual void SetViewMode()
        {
            Buttons.GetButtonByName("btnView").Enable = true;
            Buttons.GetButtonByName("btnAdd").Enable = true;
            Buttons.GetButtonByName("btnDelete").Enable = true;
            Buttons.GetButtonByName("btnEdit").Enable = true;
            Buttons.GetButtonByName("btnPrint").Enable = true;
            Buttons.GetButtonByName("btnPreview").Enable = true;
            Buttons.GetButtonByName("btnSave").Enable = false;
            Buttons.GetButtonByName("btnCancel").Enable = false;
        }



        /// <summary>
        /// 控制明细页面上的控件可被编辑.
        /// </summary>
        protected virtual void SetDetailEditorsAccessable(GroupControl gc, bool value)
        {
            if (gc == null) return;

            for (int i = 0; i < gc.Controls.Count; i++)
            {
                SetControlAccessable(gc.Controls[i], value);
            }

            controlNavigatorSummary.Enabled = !value;
        }

        /// <summary>
        /// 设置编辑控件状态.ReadOnly or Enable = false/true
        /// </summary>
        protected void SetControlAccessable(Control control, bool value)
        {
            try
            {
                if (control is Label) return;
                if (control is ControlNavigator) return;
                //if (control is LookUpEdit) return;

                if (control.Controls.Count > 0)
                {
                    foreach (Control c in control.Controls)
                        SetControlAccessable(c, value);
                }

                System.Type type = control.GetType();
                PropertyInfo[] infos = type.GetProperties();
                foreach (PropertyInfo info in infos)
                {
                    if (info.Name == "ReadOnly")//ReadOnly
                    {
                        info.SetValue(control, !value, null);
                        return;
                    }
                    if (info.Name == "Properties")//Properties.ReadOnly
                    {
                        object o = info.GetValue(control, null);
                        if (o is RepositoryItem)
                            ((RepositoryItem)o).ReadOnly = !value;
                        return;
                    }
                    if (info.Name == "Views")//OptionsBehavior.Editable
                    {
                        object o = info.GetValue(control, null);
                        if (null == o) return;
                        foreach (object view in (GridControlViewCollection)o)
                        {
                            if (view is ColumnView)
                                ((ColumnView)view).OptionsBehavior.Editable = value;
                        }
                        return;
                    }
                }
            }
            catch (Exception ex)
            { Msg.ShowException(ex); }
        }

        /// <summary>
        /// 设置Grid自定义按钮(Add,Insert,Delete)状态
        /// </summary>
        protected void SetGridCustomButtonAccessable(GridControl gridControl, bool value)
        {
            NavigatorCustomButtons custom = gridControl.EmbeddedNavigator.Buttons.CustomButtons;
            if (custom != null && custom.Count == 3)
            {
                custom[DetailButtons.Add].Enabled = value;      //add
                custom[DetailButtons.Insert].Enabled = value;   //insert
                custom[DetailButtons.Delete].Enabled = value;   //del
            }
        }

        /// <summary>
        /// 设置某个编辑控件状态.ReadOnly or Enable . (递归)循环控制
        /// </summary>
        protected void SetControlAccessableCycle(Control control, bool value)
        {
            if (control.HasChildren)
            {
                foreach (Control ctrl in control.Controls)
                {
                    //DevExpress的内部(Inner)控件
                    if (ctrl.Name == string.Empty)
                        SetControlAccessable(control, value);
                    else
                        SetControlAccessableCycle(ctrl, value);
                }
            }
            else SetControlAccessable(control, value);
        }

        /// <summary>
        /// 获取Summary表的数据. 
        /// Summary数据源必需为ArrayList对象.如果为object[],那麽为固定长度,不能插入新对象.
        /// </summary>
        protected DataTable SummaryTable
        {
            get
            {
                if (_SummaryView == null) return null;
                return (DataTable)_SummaryView.GridControl.DataSource;
            }
        }

        /// <summary>
        ///获取当前光标行的对象. 
        /// </summary>
        protected DataRow GetDataRow(int rowIndex)
        {
            if (rowIndex < 0) return null;
            if (SummaryTable != null) return SummaryTable.Rows[rowIndex];
            return null;
        }

        #region Summary数据导航功能

        /// <summary>
        /// 移到第一条记录
        /// </summary>
        protected virtual void DoMoveFirst()
        {
            if (_SummaryView == null) return;
            _SummaryView.MoveFirst();
            if (tcBusiness.SelectedTabPage != tpSummary)
                DoViewContent(null);
        }

        /// <summary>
        /// 移到上一条记录
        /// </summary>
        protected virtual void DoMovePrior()
        {
            if (_SummaryView == null) return;
            _SummaryView.MovePrev();
            if (tcBusiness.SelectedTabPage != tpSummary)
                DoViewContent(null);
        }

        /// <summary>
        /// 移到下一条记录
        /// </summary>
        protected virtual void DoMoveNext()
        {
            if (_SummaryView == null) return;
            _SummaryView.MoveNext();
            if (tcBusiness.SelectedTabPage != tpSummary)
                DoViewContent(null);
        }

        /// <summary>
        /// 移到最后一条记录
        /// </summary>
        protected virtual void DoMoveLast()
        {
            if (_SummaryView == null) return;
            _SummaryView.MoveLast();
            if (tcBusiness.SelectedTabPage != tpSummary)
                DoViewContent(null);
        }

        #endregion

        /// <summary>
        /// 第一个编辑控件设置焦点.
        /// </summary>
        protected void FocusEditor()
        {
            if (_ActiveEditor != null)
            {
                if (_ActiveEditor.CanFocus)
                    _ActiveEditor.Focus();
                else
                    this.SelectNextControl(_ActiveEditor, true, false, true, true);
            }
        }

        /// <summary>
        /// 显示明细页
        /// </summary>
        protected void ShowDetailPage(bool disableSummaryPage)
        {
            try
            {
                this.SuspendLayout();
                this.tpDetail.PageEnabled = true;
                tcBusiness.SelectedTabPage = this.tpDetail;
                tpSummary.PageEnabled = !disableSummaryPage;
                FocusEditor(); //第一个编辑框获得焦点.
                this.ResumeLayout();
            }
            catch (Exception ex)
            { Msg.ShowException(ex); }
        }
        /// <summary>
        /// 显示主表页面
        /// </summary>
        protected void ShowSummaryPage(bool disableDetailPage)
        {
            try
            {
                this.tpSummary.PageEnabled = true;
                tcBusiness.SelectedTabPage = this.tpSummary;
                tpDetail.PageEnabled = !disableDetailPage;
                if (_SummaryView.GridControl.CanFocus)
                    _SummaryView.GridControl.Focus();

            }
            catch (Exception ex)
            {
                Msg.ShowException(ex);
            }
        }

        /// <summary>
        /// 显示当前操作
        /// </summary>
        protected void ShowTip(string tip)
        {
            lblPrompt.Text = tip;
            lblPrompt.Update();
        }

        /// <summary>
        ///获取当前光标行的对象. 
        /// </summary>
        protected DataRow GetFocusedRow()
        {
            if (_SummaryView.FocusedRowHandle < 0)
                return null;
            else
            {
                if (_SummaryView.GridControl.DataSource is DataTable)
                    return _SummaryView.GetDataRow(_SummaryView.FocusedRowHandle);
                else
                    return null;
            }
        }

        private void frmBaseDataForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DataChanged)
                e.Cancel = !Msg.AskQuestion("您修改了数据没有保存，确定要退出吗?");
        }
    }

    /// <summary>
    /// 明细表Grid自定义按钮
    /// </summary>
    public class DetailButtons
    {
        public const int Add = 0;
        public const int Insert = 1;
        public const int Delete = 2;

    }
}
